package com.chuangke.dev.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.http.HttpResult;
import com.chuangke.common.utils.ConvertUtils;
import com.chuangke.common.utils.ZipUtils;
import com.chuangke.dev.bean.ImportDataRequest;
import com.chuangke.dev.model.SysModelColumn;
import com.chuangke.dev.model.SysModelTable;
import com.chuangke.dev.service.SysModelColumnService;
import com.chuangke.dev.service.SysModelTableService;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 代码生成 操作处理
 *
 * @author chuangke
 */
@RestController
@RequestMapping("dev/gen")
public class SysModelController {

    @Autowired
    private SysModelTableService genTableService;
    @Autowired
    private SysModelColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @GetMapping("/list")
    public HttpResult genList(SysModelTable genTable) {
        List<SysModelTable> list = genTableService.listModels(genTable);
        return HttpResult.ok(list);
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping(value = "/{talbleId}")
    public HttpResult getInfo(@PathVariable String talbleId) {
        SysModelTable table = genTableService.loadModelById(talbleId);
        Map<String, Object> map = new HashMap<>();
        map.put("info", table);
        map.put("rows", table.getColumns());
        return HttpResult.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list")
    public HttpResult dataList(SysModelTable genTable) {
        List<SysModelTable> list = genTableService.selectTablesFromSchema(genTable);
        return HttpResult.ok(list);
    }

    /**
     * 查询全部数据库列表
     */
    @GetMapping("/db/listAll")
    public HttpResult dataListAll(SysModelTable genTable) {
        List<SysModelTable> list = genTableService.selectAllTablesFromSchema(genTable);
        return HttpResult.ok(list);
    }

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column")
    public HttpResult columnList(@RequestParam String tableId) {
        List<SysModelColumn> list = genTableColumnService
                .list(new QueryWrapper<SysModelColumn>().lambda().eq(SysModelColumn::getTableId, tableId));
        return HttpResult.ok(list);
    }

    /**
     * 导入表结构（保存）
     */
    @GetMapping("/importTable")
    public HttpResult importTableSave(String tables) {
        String[] tableNames = ConvertUtils.toStrArray(tables);
        // 查询表信息
        List<SysModelTable> tableList = genTableService.selectTablesFromSchemaByNames(tableNames);
        genTableService.importModel(tableList);
        return HttpResult.ok();
    }

    /**
     * 创建表
     */
    @PostMapping("/createTable")
    public HttpResult createTable(@RequestBody List<SysModelColumn> sysModelColumnList) {
        genTableService.createTable(sysModelColumnList);
        return HttpResult.ok();
    }

    /**
     * 创建model中的表
     */
    @PostMapping("/createModelTable")
    public HttpResult createModelTable(@RequestBody SysModelTable sysModelTable) {
        genTableService.createModelTable(sysModelTable);
        return HttpResult.ok();
    }

    /**
     * 导入表数据
     */
    @PostMapping("/importData")
    public HttpResult importTableData(ImportDataRequest importDataRequest, MultipartFile file) {
        genTableService.importTableData(importDataRequest, file);
        return HttpResult.ok();
    }

    /**
     * 查询表数据
     */
    @PostMapping("/findImportData")
    public HttpResult findImportData(@RequestBody Map<String, Object> params) {
        return HttpResult.ok(genTableService.findImportData(new CkPageQuery(params)));
    }

    /**
     * 修改保存代码生成业务
     */
    @PutMapping
    public HttpResult editSave(@Validated @RequestBody SysModelTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateModel(genTable);
        return HttpResult.ok();
    }

    /**
     * 删除代码生成
     */
    @PostMapping("/delTable")
    public HttpResult remove(@RequestBody List<String> tableIds) {
        genTableService.deleteModelByIds(tableIds);
        return HttpResult.ok();
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview/{tableId}")
    public HttpResult preview(@PathVariable("tableId") String tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return HttpResult.ok(dataMap);
    }

    /**
     * 生成代码
     */
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) {
        Map<String, byte[]> fileMap = genTableService.generatorCode(tableName);
        ZipUtils.downloadFileZip(response, "chuangke", fileMap);
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tableId) {
        String[] tableIds = ConvertUtils.toStrArray(tableId);
        Map<String, byte[]> fileMap = genTableService.generatorCode(tableIds);
        ZipUtils.downloadFileZip(response, "chuangke", fileMap);
    }

}